package com.asiainfo.hybridapp.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asiainfo.hybridapp.R;
import com.asiainfo.hybridapp.configs.ConstantsME;
import com.asiainfo.hybridapp.configs.DebugConfig;
import com.asiainfo.hybridapp.configs.EventBusTag;
import com.asiainfo.hybridapp.configs.IntentCode;
import com.asiainfo.hybridapp.configs.InterfaceConfig;
import com.asiainfo.hybridapp.configs.RealInterfaceConfig;
import com.asiainfo.hybridapp.networkModel.HttpUtil;
import com.framework.customviews.OverScrollView;
import com.framework.security.RSAmethodInRaw;
import com.framework.utils.KeyBoardUtil;
import com.framework.utils.PreferencesHelper;
import com.framework.utils.RegularUtil;
import com.framework.utils.RequestPermissionsUtil;
import com.framework.utils.ScreenUtils;
import com.framework.utils.ToastUtil;
import com.framework.utils.Y;
import com.framework2.utils.CookieManagerUtil;
import com.framework2.utils.CustomProgressDialogUtils;
import com.framework2.utils.EncStringUtil;
import com.framework2.utils.PicToastUtil;
import com.framework2.utils.TBSCookieManagerUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import custom.org.greenrobot.eventbus.Subscribe;
import custom.org.greenrobot.eventbus.ThreadMode;

/**
 * 登录注册
 *
 * @author Yangjie
 * className LoginActivity
 * created at  2017/3/13  16:24
 */
public class LoginActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    @BindView(R.id.etLoginPhone)
    EditText etLoginPhone;
    @BindView(R.id.etLoginPassword)
    EditText etLoginPassword;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.loginLayout)
    LinearLayout loginLayout;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.overScrollView)
    OverScrollView overScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((DebugConfig.TBSx5 && !TextUtils.isEmpty(TBSCookieManagerUtil.getInstance().decodeCookie(this,
                PreferencesHelper.getInstance().getStringData(ConstantsME.cookies))))
                || (!DebugConfig.TBSx5 && !TextUtils.isEmpty(CookieManagerUtil.getInstance().decodeCookie(this,
                PreferencesHelper.getInstance().getStringData(ConstantsME.cookies))))) {
            RealInterfaceConfig.setBaseServerUrl(EncStringUtil.getInstance().getString(LoginActivity.this,
                    ConstantsME.url));
            startActivity(HomepageActivity.class);
            finish();
        }
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        ScreenUtils.getInstance().setTranslucentStatus(this, true);
        ScreenUtils.getInstance().setStatusBarTintColor(this,
                getResources().getColor(R.color.main));
        initData();
        initEvent();
        RequestPermissionsUtil.getInstance().checkPermissionsThenRequest(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                RequestPermissionsUtil.PERMISSION_WRITE_READ_EXTERNAL_STORAGE);
    }

    private void initData() {
        overScrollView
                .setOverScrollTinyListener(new OverScrollView.OverScrollTinyListener() {
                    @Override
                    public void scrollLoosen() {

                    }

                    @Override
                    public void scrollDistance(int tinyDistance,
                                               int totalDistance) {
                        KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this,
                                etLoginPhone, true);
                    }
                });
        String phone = RSAmethodInRaw.rsaDecrypt(this,
                PreferencesHelper.getInstance().getStringData(ConstantsME.PHONE));
        if (!TextUtils.isEmpty(phone)) {
            etLoginPhone.setText(phone);
            etLoginPhone.setSelection(phone.length());
            etLoginPhone.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, etLoginPhone, false);
        }
        if (!TextUtils.isEmpty(phone)) {
            etLoginPhone.setText(phone);
            etLoginPhone.setSelection(phone.length());
            etLoginPassword.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this,
                    etLoginPhone, true);
        }
    }

    private void initEvent() {
        etLoginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvForgetPwd.setVisibility((s != null && !TextUtils.isEmpty(s)) ? View.GONE : View.VISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private boolean isLegal(EditText et_phone, EditText et_password, EditText et_captcha) {
        if (null == et_phone || null == et_password)
            return false;
        if (TextUtils.isEmpty(et_phone.getText())) {
            PicToastUtil.showPicToast(LoginActivity.this, "请输入你的手机号码!");
            et_phone.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, et_phone, false);
            return false;
        } else if (!RegularUtil.getInstance().isMobileNO(et_phone.getText().toString())) {
            PicToastUtil.showPicToast(LoginActivity.this, "请输入正确的手机号码!");
            et_phone.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, et_phone, false);
            return false;
        } else if (TextUtils.isEmpty(et_password.getText())) {
            PicToastUtil.showPicToast(LoginActivity.this, "请输入密码!");
            et_password.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, et_phone, false);
            return false;
        } else if (null != et_captcha && !TextUtils.isEmpty(et_captcha.getText())) {
            PicToastUtil.showPicToast(LoginActivity.this, "请输入验证码!");
            et_captcha.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, et_phone, false);
            return false;
        }
        return true;
    }

    //eventBus通知 getShopIdSuccess
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.getShopIdSuccess)
    public void getShopIdSuccess(String info) {

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_forget_pwd:
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, etLoginPhone, true);
                Bundle forgetBundle = new Bundle();
                if (!TextUtils.isEmpty(etLoginPhone.getText()) && RegularUtil.getInstance().isMobileNO(etLoginPhone.getText().toString()))
                    forgetBundle.putString(ConstantsME.PHONE, etLoginPhone.getText().toString());
                startActivityForResult(ForgetPasswordActivity.class, forgetBundle, IntentCode.login);

                break;
            case R.id.tv_login:
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, etLoginPhone, true);
                if (isLegal(etLoginPhone, etLoginPassword, null)) {
                    CustomProgressDialogUtils.showProcessDialog(LoginActivity.this, "正在登录");
                    requestLogin();
                }
                RealInterfaceConfig.setBaseServerUrl(etLoginPhone.getText().toString());
                EncStringUtil.getInstance().putString(LoginActivity.this, etLoginPhone.getText().toString(),
                        ConstantsME.url);
                startActivity(HomepageActivity.class);
                finish();
                break;

            default:
                break;
        }
    }

    /**
     * login
     */
    private void requestLogin() {
        HttpUtil.getInstance().requestLogin(InterfaceConfig.login, etLoginPhone.getText().toString(),
                etLoginPassword.getText().toString(), new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... msg) {
                        CustomProgressDialogUtils.dismissProcessDialog();
                        PreferencesHelper.getInstance().putInfo(ConstantsME.PHONE,
                                RSAmethodInRaw.rsaEncrypt(LoginActivity.this, etLoginPhone.getText().toString()));
                        PreferencesHelper.getInstance().putInfo(ConstantsME.token, msg != null ? msg[0] : "");
                        PreferencesHelper.getInstance().putInfo(ConstantsME.nick, msg != null ? msg[1] : "");
                        PreferencesHelper.getInstance().putInfo(ConstantsME.imgUrl, msg != null ? msg[2] : "");
                        PreferencesHelper.getInstance().putInfo(ConstantsME.LOGINED, true);

                        CustomProgressDialogUtils.showProcessDialog(LoginActivity.this, "检查店铺");
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        CustomProgressDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "登录失败" : msg);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Y.y("Homepage--onRequestPermissionsResult:" + requestCode);
        if (requestCode == RequestPermissionsUtil.PERMISSION_WRITE_READ_EXTERNAL_STORAGE) {
            if ((grantResults.length > 1) && (grantResults[0] == PackageManager.PERMISSION_GRANTED) && (grantResults[1] == PackageManager.PERMISSION_GRANTED)) {

            } else {
                ToastUtil.getInstance().showToast("存储权限未开启，请手动开启");
                RequestPermissionsUtil.getInstance().showInstalledAppDetailSettingIntent(this, getPackageName());
            }
        }
    }
}
